'''
Created on Aug 14, 2012

@author: alebalbin
'''
import os
import sys
import glob
import numpy as np
from collections import defaultdict

class mic_record():
            
    def __init__(self,var1,var2,fields):
        '''
        transcript_id
        '''
        self.var1=var1
        self.var2=var2
        self.mic=fields[0]
        self.mic_p2=fields[1]
        self.mas=fields[2]
        self.mev=fields[3]
        self.mcn=fields[4]
        self.p=fields[5]
        return

class expMatrix:
    def __init__(self,n,m,record_list):
        self.mat = np.zeros((n,m),dtype=np.float)
        #self.variables= np.empty((n,2),dtype=str)
        self.variables=defaultdict(list)
        # Fill the matrix
        self.fill_expr_mat(record_list)
        
    def fill_expr_mat(self,record_list):
        # row_ind is a counter for all the rows in the datamatrix
        i=0
        for record in record_list:
            #self.variables[i,0],self.variables[i,1]=record.var1,record.var2
            self.variables[i]=[record.var1,record.var2]
            self.mat[i,0],self.mat[i,1],self.mat[i,2],self.mat[i,3],self.mat[i,4],self.mat[i,5]=\
            record.mic,record.mic_p2,record.mas,record.mev,record.mcn,record.p
            i+=1
    def write_mic_matrix(self,output_file):
        '''
        Write the consolidated matrix of MIC
        '''
        ofile=open(output_file,'w')
        hd = ['Xvar','Yvar','MIC(strength)','MIC-p^2(nonlinearity)',
              'MAS(non-monotonicity)','MEV(functionality)','MCN(complexity)','Linear_regression(p)']
        ofile.write(",".join(hd).replace(',', '\t')+'\n')
        
        for i in range(self.mat.shape[0]):
            #ol = list(map(str,self.variables[i,:])) + list(map(str,self.mat[i,:]))
            ol = self.variables[i] + list(map(str,self.mat[i,:]))
            ofile.write(",".join(ol).replace(',', '\t')+'\n')
        ofile.close()

'''    
def read_gtf(gtf_file):
    for line in gtf_file:
        fields = line.strip('\n').split('\t')
        yield gtf_transcript(fields)
'''
        
def read_files_folder(folderpath,ext):
    myfiles=[]
    for infile in glob.glob(os.path.join(folderpath,'*'+ext)):
        myfiles.append(infile)
    return myfiles

def read_mic_file(file_lines,v1=None,v2=None):
    
    for l in file_lines:
        f=l.strip('\n').split(',')
        if v1 is not None and v2 is not None:
            var1,var2=v1,v2
        else:
            var1,var2=f[0],f[1]
        f=f[2:]
        yield mic_record(var1,var2,f)

def build_MIC_list(ifile):
    mic_file=open(ifile)
    file_lines=mic_file.readlines()
    hd= file_lines.pop(0)
    vars=ifile.split('/')[-1].split(',')[0].split('_vs_')
    v2=vars[1].strip().split(' ')
    v2=("%s_%s")%(v2[0],v2[1])
    v1= vars[0].split('_')[2].split(' ')
    v1=("%s_%s")%(v1[0],v1[1])
    if len(file_lines)==0:
        f=[0,0,0,0,0,0,0]
        record=mic_record(v1,v2,f)
    else:
        for record in read_mic_file(file_lines,v1,v2):
            pass
        #print v1,v2,record
    return record
    mic_file.close()

if __name__ == '__main__': 
    '''
    files_list=['/Users/alebalbin/Documents/projects/lungseq/transcriptome_analysis/MINE_results/MINE2_results_ sense_27328 _vs_ asense_27328,0-vs-1,cv=0.0,B=n^0.6,Results.csv',
                '/Users/alebalbin/Documents/projects/lungseq/transcriptome_analysis/MINE_results/MINE2_results_ sense_27803 _vs_ asense_27803,0-vs-1,cv=0.0,B=n^0.6,Results.csv']
    outfile='/Users/alebalbin/Documents/projects/lungseq/transcriptome_analysis/MINE_results/mic_matrix.txt'
    '''
    #folderparth='/Users/alebalbin/Documents/projects/lungseq/transcriptome_analysis/MINE_results/'
    folderparth='/exds/users/oabalbin/projects/lungseq/MINE_results_v0.2.0/mic_results/'
    outfile=os.path.join(folderparth,'mic_matrix.txt')
    ext='Results.csv'
    files_list = read_files_folder(folderparth,ext)
    record_list = [build_MIC_list(f) for f in files_list]

    m=expMatrix(len(record_list),6,record_list)
    m.write_mic_matrix(outfile)